/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.news;

import java.net.URL;
import java.util.List;

import android.app.ActionBar;
//import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;


public class MainActivity extends FragmentActivity {
    private View mActionBarView;
    private WebViewFragment mWebViewFragment;
    DetailsFragment mDetailsFragment;
    CategoryFragment mCategoryFragment;
    protected Bundle savedInstanceState = null;
    protected int mContainerId;
    protected boolean mSinglePane;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        this.savedInstanceState = savedInstanceState;
        setContentView(R.layout.main);
        ViewGroup container = (ViewGroup) findViewById(R.id.container_fragment);
        if(container != null) {
            mContainerId = R.id.container_fragment;
            mSinglePane = true;
        }else {
            mContainerId = R.id.details_fragment;
        }
        mDetailsFragment = (DetailsFragment) getSupportFragmentManager().findFragmentById(
                mContainerId);
        Directory.initializeDirectory(this);
        if(Build.VERSION.SDK_INT >= 11) {
            ActionBar bar = getActionBar();

            bar.setCustomView(mActionBarView);
            bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_USE_LOGO);
            bar.setDisplayShowHomeEnabled(true);
        }
        loadFragments();
  }
    
    public void onStart() {
        super.onStart();
        setProgressBarIndeterminateVisibility(false); 
    }
    
    public void onSaveInstanceState(Bundle bundle) {
        Fragment fragment = this.getSupportFragmentManager().findFragmentById(
                mContainerId);
        String clazz = fragment.getClass().getName();
        bundle.putString("DetailsFragment", clazz);
        if(clazz.endsWith("WebViewFragment")) {
            String url = ((WebViewFragment)fragment).getUrl();
            bundle.putString("url", url);
        } 
    }

    
    private void loadFragments() { 
        try { 
            if(mSinglePane) {
                mCategoryFragment  = new CategoryFragment();
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.add(R.id.container_fragment, mCategoryFragment);
                fragmentTransaction.addToBackStack("CategoryFragment");
                fragmentTransaction.commit();
               
            }else {
                mDetailsFragment = new DetailsFragment();
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.add(mContainerId, mDetailsFragment);
                fragmentTransaction.addToBackStack("DetailsFragment");
                fragmentTransaction.commit();
                mCategoryFragment = (CategoryFragment) getSupportFragmentManager()
                .findFragmentById(R.id.category_fragment);
                mCategoryFragment.populateTitles();
                mCategoryFragment.selectPosition(0);
            }
        }catch(Exception e) {
            Log.e(MainActivity.class.getName(), e.toString(),e);
        }
    }
    
    protected void loadWebViewFragment(String url) {
        if(mWebViewFragment == null) {
            mWebViewFragment = new WebViewFragment();
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(mContainerId, mWebViewFragment);
        fragmentTransaction.addToBackStack("WebViewFragment");
        fragmentTransaction.commit();
        
        mWebViewFragment.setUrl(url);
    }
}

class DownloadFilesTask extends AsyncTask<URL, Integer, List> {
    private static final String TAG = "DownloadFilesTask";
    private MainActivity mActivity;
    public DownloadFilesTask(MainActivity activity) {
        mActivity = activity;
        mActivity.setProgressBarIndeterminateVisibility(true);
       
    }
    @SuppressWarnings("rawtypes")
    protected List doInBackground(URL... url) {
        List output = Downloader.downloadFile(url[0]);
        return output;
    }

    protected void onProgressUpdate(Integer... progress) {
        setProgressPercent(progress[0]);
    }

    private void setProgressPercent(final Integer integer) {
        mActivity.setProgress(100*integer);
    }

    protected void onPostExecute(List output) {
        Log.i(TAG, "onPostExecute:begin");
        mActivity.setProgress(100);
        mActivity.setProgressBarIndeterminateVisibility(false);
        FragmentManager fragmentManager = mActivity.getSupportFragmentManager();

        DetailsFragment detailsFragment = new DetailsFragment();
        FragmentTransaction fragmentTransactionTwo = fragmentManager.beginTransaction();

        fragmentTransactionTwo.replace(mActivity.mContainerId, detailsFragment);

        fragmentTransactionTwo.addToBackStack("DetailsFragment");
        fragmentTransactionTwo.commit();
        detailsFragment.setDataList(output);

        Log.d(TAG, "mCategoryFragment:" + mActivity.mCategoryFragment);
        Log.d(TAG, "mCategory:" + mActivity.mCategoryFragment.mCategory);
        DirectoryEntry entry = mActivity.mCategoryFragment.mCategoryEntryObj.get(mActivity.mCategoryFragment.mCurPosition);
    
        entry.setNewsItems(output);
        entry.setLastUpdatedTime(System.currentTimeMillis());

        Log.i(TAG, "onPostExecute:end");
    }
}